Vue.component('yl-button', {
    template: `
    <span>
        <el-button :type="type" @click="Export" :loading="loading">
            <slot></slot>
        </el-button>
        <el-table id="ExportData" :data="data" style="display: none; width: 100%;margin-bottom: 20px;">
            <el-table-column label="序号"type="index"></el-table-column>
            <el-table-column prop="Supplier_Article_SerialNumber" label="供应商品内码"></el-table-column>
            <el-table-column prop="Article_SerialNumber" label="商品内码"></el-table-column>
            <el-table-column prop="Article_Specifications_SerialNumber" label="规格内码"></el-table-column>
            <el-table-column prop="Supplier_SerialNumber" label="供应商内码"></el-table-column>
            <el-table-column prop="Supplier_Name" label="供应商"></el-table-column>
            <el-table-column prop="Article_Name" label="商品名称"></el-table-column>
            <el-table-column prop="Specifications_Name" label="规格名称"></el-table-column>
            <el-table-column prop="Picture_URL" label="图片">
                <template v-slot="{row}">
                    {{row.Picture_URL? BASE_IMG +row.Picture_URL:'否'}}
                </template>
            </el-table-column>
            <el-table-column prop="Brand_Name" label="品牌名称"></el-table-column>
            <el-table-column prop="Brand_SerialNumber" label="品牌内码"></el-table-column>
            <el-table-column prop="Total_stock" label="今日上架库存"></el-table-column>
            <el-table-column prop="Stock_Remain" label="当日剩余库存"></el-table-column>
            <el-table-column prop="Stock_Sell" label="当日已售"></el-table-column>
            <el-table-column prop="Shelf" label="是否上架">
                <template v-slot="{row}">
                    {{row.Shelf=='0'?'是':'否'}}
                </template>
            </el-table-column>
            <el-table-column prop="Shelf_Date" label="上/下架操作时间"></el-table-column>
            <el-table-column label="导出时间">
                <template v-slot="{row}">
                    {{getYMDHMSDate()}}
                </template>
            </el-table-column>
        </el-table>
    </span>`,
    props: ['loading', 'data', 'type'],
    methods: {
        Export() {
            this.$emit('click')
        }
    }
})
new Vue({
    el: '#app',
    data() {
        return {
            form: {
                SQLSerialNumber: "P_business_supplier_article",
                PaginationNumber: 1,//页数
                RowAmount: 10,//每页数据条数
                Article_Name: '',
                selectScreen: '',
                Supplier_SerialNumber: '',
                Brand_SerialNumber: '',
                ExtensionCondition: '',
                Condition: ''
            },
            total: 0,
            tableData: [],	//表格数据
            treeData: [],
            multipleSelection: [],
            ExportData: [],//导出
            loading: false,
            defaultProps: {
                children: 'Children',
                label: 'Brand_Name'
            },
            screen: [{
                label: '采购价格高到低',
                value: '0'
            }, {
                label: '采购价格低到高',
                value: '1'
            }],
            supplier: [],
            isTree: true,
        }
    },
    mounted() {
        this.getData();
        this.getList(this.form);//前端分页
    },
    methods: {
        onSerach() {			//查询方法
            this.form.PaginationNumber = 1;
            this.getList(this.form)
        },
        showTree() {
            this.isTree = !this.isTree
        },
        getData() {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                type: 'POST',
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                data: {
                    Data: 'business_supplier_info',
                    Condition: "Row_Status='0'"
                },
                success: function (Result) {
                    that.supplier = Result
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/article/BrandTreeOfSuppliers`,
                type: 'GET',
                success: function (data) {
                    data.forEach(item => {
                        item.TreeNode = item.Supplier_SerialNumber
                        item.Brand_Name = item.Supplier_Name
                    });
                    that.treeData = data;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },

        Add() {
            window.location.href = './add.html'
        },
        handleSizeChange(val) {
            this.form.PaginationNumber = 1;
            this.form.RowAmount = val;
            this.getList(this.form)
        },
        handleCurrentChange(val) {
            this.form.PaginationNumber = val;
            this.getList(this.form)
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        downloadTemplate(command) {
            if (command == "Article") {
                window.location.href = './download/导入供应商经营商品模板.xlsx';
            }
        },
        importTemplate(command) {
            if (command == "Article") {
                window.location.href = './import_article.html';
            }
        },
        handleBatchAdd(command) {
            const that = this;
            if (this.multipleSelection.length > 0) {
                this.$confirm(command == '0' ? '是否将勾选的商品下架?' : '是否将勾选的商品上架', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'info'
                }).then(() => {
                    //1.遍历已选查询对应数据
                    let Shelf_Date = getYMDHMSDate();
                    let Condition = "";
                    this.multipleSelection.filter(i => i.Shelf == command).forEach(item => {
                        if (Condition) {
                            Condition = Condition + " OR Supplier_Article_SerialNumber='" + item.Supplier_Article_SerialNumber + "'"
                        } else {
                            Condition = "Supplier_Article_SerialNumber='" + item.Supplier_Article_SerialNumber + "'"
                        }
                    });
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${BASE_URL2}/generalBusiness/generalQueryByTableNameWithOriginal`,
                        type: 'POST',
                        data: {
                            Data: 'business_supplier_article',
                            Condition
                        },
                        success: function (business_supplier_article) {
                            let base_operation_log = [];
                            business_supplier_article.forEach(item => {
                                item.Shelf = (command == '0' ? '1' : '0');
                                item.Shelf_Date = Shelf_Date;
                                base_operation_log.push(generateLog('商品:'+that.multipleSelection.filter(i=>i.Supplier_Article_SerialNumber == item.Supplier_Article_SerialNumber)[0].Article_Name+'(供应商:'+that.multipleSelection.filter(i=>i.Supplier_Article_SerialNumber == item.Supplier_Article_SerialNumber)[0].Supplier_Name+')'+(command == '0' ? '下' : '上')+'架', '平台端操作', 'business_supplier_article', JSON.stringify({  Modify: { business_supplier_article:item } })))
                            })   
                            $.ajax({
                                headers: requestHeaders(),
                                url: `${BASE_URL2}/generalBusiness/generalSave`,
                                type: 'POST',
                                data: {
                                    Data: JSON.stringify({ 
                                        Modify: { business_supplier_article } ,
                                        Add: { base_operation_log }
                                    })
                                },
                                success: function (res) {
                                    if (res.Status === 'success') {
                                        that.$message({
                                            type: 'success',
                                            message: '操作成功!'
                                        });
                                        that.getList(that.form);
                                    } else {
                                        that.$message.error("删除失败，请稍后再试")
                                    }
                                },
                                error: function () {
                                    that.$message.error("删除失败，请稍后再试")
                                },
                                complete: function (XMLHttpRequest) {
                                    that.loading = false
                                    requestPretreatment(XMLHttpRequest);
                                },
                                dataType: "json"
                            })
                        },
                        error: function () {
                            that.$message.error("删除失败，请稍后再试")
                        },
                        complete: function (XMLHttpRequest) {
                            that.loading = false
                            requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json"
                    })
                }).catch(() => { });
            } else {
                this.$message({
                    type: 'warning',
                    message: '至少要选择1个商品!'
                });
            }
        },
        getList(form) {//换页方法
            const that = this
            let data = deepClone(form);
            data.Condition = window.btoa(unescape(encodeURIComponent("%" + data.Article_Name + "%")));
            let sql = "";
            if (data.Supplier_SerialNumber) {
                sql = sql + "and business_supplier_article.Supplier_SerialNumber = '" + data.Supplier_SerialNumber + "'\r\n";
            }
            if (data.Brand_SerialNumber) {
                sql = sql + "and business_article_info.Brand_SerialNumber = '" + data.Brand_SerialNumber + "'\r\n";
            }
            if (data.selectScreen != '') {//筛选
                if (data.selectScreen == '0') {
                    sql = sql + "ORDER BY business_daily_purchase_unitprice.Purchase_Unit_Price DESC,business_supplier_article.Article_SerialNumber DESC,business_supplier_article.Article_Specifications_SerialNumber"
                } else if (data.selectScreen == '1') {
                    sql = sql + "ORDER BY business_daily_purchase_unitprice.Purchase_Unit_Price,business_supplier_article.Article_SerialNumber DESC,business_supplier_article.Article_Specifications_SerialNumber"
                }
            } else {
                sql = sql + "ORDER BY business_supplier_article.Article_SerialNumber DESC,business_supplier_article.Article_Specifications_SerialNumber"
            }
            data.ExtensionCondition = window.btoa(unescape(encodeURIComponent(sql)));
            $.ajax({
                headers: requestHeaders(),
                type: 'POST',
                url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
                data,
                success: function (Result) {
                    console.log(Result);
                    that.tableData = Result.Rows;
                    that.total = Result.TotalRows;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        Edit(Article_SerialNumber) {
            sessionStorage.setItem("Article_SerialNumber", Article_SerialNumber)
            window.location.href = './edit.html?Article_SerialNumber=' + Article_SerialNumber
        },
        Remove(row) {
            const that = this;
            let obj = deepClone(row);
            console.log(obj);
            this.$confirm(`是否要${obj.Shelf == '0' ? '下' : '上'}架该商品继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                obj.Shelf_Date = getYMDHMSDate();
                $.ajax({
                    headers: requestHeaders(),
                    url: `${BASE_URL2}/generalBusiness/generalQueryByTableNameWithOriginal`,
                    type: 'POST',
                    data: {
                        Data: 'business_supplier_article',
                        Condition: "Supplier_Article_SerialNumber='" + row.Supplier_Article_SerialNumber + "'"
                    },
                    success: function (data) {
                        if (obj.Shelf == '0') {
                            data[0].Shelf = '1'
                        } else {
                            data[0].Shelf = '0'
                        }
                        $.ajax({
                            headers: requestHeaders(),
                            url: `${BASE_URL2}/generalBusiness/generalSave`,
                            type: 'POST',
                            data: {
                                Data: JSON.stringify({
                                    Modify: { business_supplier_article: data },
                                    Add: { base_operation_log:[generateLog('商品:'+obj.Article_Name+'(供应商:'+obj.Supplier_Name+')'+(obj.Shelf == '0' ? '下' : '上')+'架', '平台端操作', 'business_supplier_article', JSON.stringify({  Modify: { business_supplier_article:data } }))] }
                                })
                            },
                            success: function (res) {
                                if (res.Status === 'success') {
                                    that.$message({
                                        type: 'success',
                                        message: '操作成功!'
                                    });
                                    that.getList(that.form);
                                } else {
                                    that.$message.error("删除失败，请稍后再试")
                                }
                            },
                            error: function () {
                                that.$message.error("删除失败，请稍后再试")
                            },
                            complete: function (XMLHttpRequest) {
                                that.loading = false
                                requestPretreatment(XMLHttpRequest);
                            },
                            dataType: "json"
                        })
                    },
                    error: function () {
                        that.$message.error("删除失败，请稍后再试")
                    },
                    complete: function (XMLHttpRequest) {
                        that.loading = false
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json"
                })

            }).catch(() => { });
        },
        handleExpandChange(row) {
            console.log(row);
        },
        handleNode(row, node) {
            this.form.Supplier_SerialNumber = row.Supplier_SerialNumber
            this.form.Brand_SerialNumber = row.Brand_SerialNumber
            this.getList(this.form);
        },
        Export(form) {
            const that = this;
            this.loading = true;
            let data = deepClone(form);
            data.Condition = window.btoa(unescape(encodeURIComponent("%" + data.Article_Name + "%")));
            let sql = "";
            if (data.Supplier_SerialNumber) {
                sql = sql + "and business_supplier_article.Supplier_SerialNumber = '" + data.Supplier_SerialNumber + "'\r\n";
            }
            if (data.Brand_SerialNumber) {
                sql = sql + "and business_article_info.Brand_SerialNumber = '" + data.Brand_SerialNumber + "'\r\n";
            }
            data.ExtensionCondition = window.btoa(unescape(encodeURIComponent(sql)));
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                type: 'POST',
                data,
                success: function (Result) {
                    if (Result.length > 0) {
                        that.ExportData = Result;
                        that.$nextTick(() => {
                            let wb = XLSX.utils.table_to_book(document.querySelector("#ExportData"));
                            var wbout = XLSX.write(wb, {
                                bookType: "xlsx",
                                bookSST: true,
                                type: "array"
                            });
                            try {
                                saveAs(
                                    new Blob([wbout], {
                                        type: "application/octet-stream"
                                    }),
                                    "供应商品信息表" + (+new Date()) + ".xlsx"
                                );
                            } catch (e) {
                                if (typeof console !== "undefined") console.log(e, wbout);
                            }
                            that.$message({
                                message: '已成功导出',
                                type: 'success'
                            })
                            return wbout;
                        })
                    } else {
                        that.$message({
                            message: '暂无可导出的数据',
                            type: 'warning'
                        })
                    }
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false;
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        }
    },
})